﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO.IsolatedStorage;
using System.IO;
using System.Windows.Resources;
using System.Xml.Linq;
using System.Linq;
using System.Collections.Generic;
using System.Reflection;
using System.Diagnostics;

namespace WidgetLibrary
{
    //**********************************************************************************************
    // This copy all files under "Widget" directory into Isolated Storage of the Application.
    // Read the XML wich describes the folder's structure.
    // This XML its automatically create with XMLCreate.exe
    // IMPORTANT: Build Action should be set in Content for All resources that you want copy (All Files in Widget Folder)
    //**********************************************************************************************

    /// <summary>
    /// Load widget in device the first time.
    /// </summary>
    public static class Loader
    {
        public static void LoadResources()
        {
            LoadResourcesFromDisk();
        }


        private static void LoadResourcesFromDisk()
        {
            // If Isolated Storage contains "Widget" folder, the widget has been load.
            //if (!IsolatedStorageFile.GetUserStoreForApplication().DirectoryExists("Widget"))
            //{
                XElement widgetXml;

                // Read Widget.xml placed in Widget Folder. 
                StreamResourceInfo xml = Application.GetResourceStream(new Uri("Widget/Widget.xml", UriKind.Relative));
                widgetXml = XElement.Load(xml.Stream);

                // Copy files 
                CopyFilesRecursive(widgetXml, "Widget");
            //}
        }


        /// <summary>
        /// Read the xml and write the files in Isolated Storage
        /// </summary>
        /// <param name="widgetXml">xml wich describes widget items</param>
        /// <param name="basePath">path to write the file</param>
        private static void CopyFilesRecursive(XElement widgetXml, string basePath)
        {
            foreach (XElement item in widgetXml.Elements())
            {
                if (item.Name == "File")
                    WriteFile(IsolatedStorageFile.GetUserStoreForApplication(), basePath, item.Value);                    
                else
                    CopyFilesRecursive(item, basePath + "/" + item.Name);
            }
        }      

        /// <summary>
        /// Read a file in resources and write in Isolated Storage
        /// </summary>
        /// <param name="store">IsolatedStorageFile for User Application</param>
        /// <param name="baseDir">Base path to write the file</param>
        /// <param name="filename">Filename</param>
        private static void WriteFile(IsolatedStorageFile store, string baseDir, string filename)
        {
            if (!store.FileExists(baseDir + "/" + filename))
            {
                if (!store.DirectoryExists(baseDir))
                    store.CreateDirectory(baseDir);

                // Load an resource file sited in the application assembly.
                Uri uri = new Uri(baseDir + "/" + filename, UriKind.Relative);
                StreamResourceInfo sri = Application.GetResourceStream(uri);
                Stream strm = sri.Stream;


                // Obtain an isolated store for an application.
                try
                {
                    using (var isoStream = store.OpenFile(baseDir + "/" + filename, FileMode.OpenOrCreate))
                    {
                        // Read the resource file into a byte array.
                        byte[] bytes = new byte[strm.Length];
                        int numBytesToRead = (int)strm.Length;
                        int numBytesRead = 0;
                        while (numBytesToRead > 0)
                        {
                            // Read may return anything from 0 to numBytesToRead.
                            int n = strm.Read(bytes, numBytesRead, numBytesToRead);
                            // The end of the file is reached.
                            if (n == 0)
                                break;
                            numBytesRead += n;
                            numBytesToRead -= n;
                        }


                        numBytesToRead = bytes.Length;

                        // Write the byte array to the IsolatedStorageFileStream.
                        isoStream.Write(bytes, 0, numBytesToRead);

                        Debug.WriteLine("Write File OK: " + baseDir + "/" + filename + "-> Size: " + numBytesRead + "bytes");

                    }
                    strm.Close();
                }
                catch (IsolatedStorageException isx)
                {
                    Debug.WriteLine(isx.InnerException);
                }
            }
        }
        


    }
}
